import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/throw'
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
import { Http, RequestOptions, ResponseContentType, RequestMethod, Headers } from '@angular/http';
import { appConfig } from '../config/app.config'
import { ServerConfig } from '../config/server'
// import { Store } from '@ngrx/store';
// import { State } from '../store';
// import {StorageService} from './storage.service'



@Injectable()
export class NetService {
  headers = new Headers()
  user: Observable<Object>
  token: string

  constructor(
    private http: Http,
    // private store: Store<State>,
    // private storage:StorageService
  ) {
    // 默认用token
    // this.token = storage.getItem('userToken')
    // 如果更新使用store中的token
    // store.select('user').subscribe((user) => {
    //   if (user) {
    //     this.token = user.token.toString()
    //   }
    // })
  }

  /**
   * 根据服务配置生成通讯地地址
   * @param options
   */
  private generateRequestUrl(options: ServerConfig, append: Array<String> = []): string {
    return [
      appConfig.url.server,
      options.controller,
      options.action,
      ...append].filter(x => x).join('/')
  }
  U
  /**
   * 根据服务配置返回Search参数
   * @param options
   */
  private generateRequestSearch(options): object {
    if ([RequestMethod.Get, RequestMethod.Delete].includes(options.service.method)) {
      if (options.page) {
        Object.assign(options.params || {}, options.page.getConfig())
      }
      return options.params
    } else {
      return null
    }
  }

  /**
   * 根据服务配置返回Body参数
   * @param options
   */
  private generateRequestBody(options): object {
    if ([RequestMethod.Post, RequestMethod.Put].includes(options.service.method)) {
      if (options.page) {
        Object.assign(options.params || {}, options.page.getConfig())
      }
      return options.params
    } else {
      return null
    }
  }

  /**
   * 生成头部信息
   */
  private generateRequestHeader() {
    if (this.token) {
      this.headers.set('X-OperatorToken', this.token)
    } else {
      this.headers.delete('X-OperatorToken')
    }
    return this.headers
  }

  /**
   * 发送网络通讯请求
   * @param options
   */
  send(options: any):Observable<any> {
    // if(options.service.action === 'login'){
    //   this.token = ''
    // }
    let requestUrl: string = this.generateRequestUrl(options.service, options.append)
    let requestOptions: RequestOptions = new RequestOptions({
      method: options.service.method,
      search: this.generateRequestSearch(options),
      body: this.generateRequestBody(options),
      responseType: ResponseContentType.Json,
      headers: this.generateRequestHeader()
    })

    // 生车通讯观察对象
    var observable = Observable.create((observer) => {
      console.log(requestUrl)
      this.http.request(requestUrl, requestOptions)
        .map(response => response.json())
        .catch(response => {
          console.log(response)
          try {
            return Observable.throw('error')
          } catch (ex) {
            return Observable.throw("网络通讯异常")
          }
        })
        .subscribe((data) => {
          // 判断是否开启分页
          if (options.page && data.content) {
            options.page.update(data)
            data = data.content
          }

          observer.next(data)
        })
    });

    return observable
  }
}
